专题七:查找

查找的内容包括以下几个部分:

首先要区分什么是静态查找和动态查找

顺序查找就不说了 没啥好说的

折半查找:其实就是二分查找 思路也不说了 这里说一下代码:

而且其实二分查找有有三种 因为有的是不严格递增的 查左端点还是右端点的区别

int binarySearch(vector<int>& nums, int target) {
    int left = 0; 
    // 注意
    int right = nums.size() - 1;

    while(left <= right) {
        int mid = left + (right - left) / 2;
        if(nums[mid] == target)
            return mid; 
        else if (nums[mid] < target)
            // 注意
            left = mid + 1;
        else if (nums[mid] > target)
            // 注意
            right = mid - 1;
    }
    return -1;
}

分块查找之前没有接触过:

分块查询实际上是一种结合了顺序查询和折半查找优点的查找技术

在分块查询中,数据被分成若干个“块”或者“桶”,每个块内的元素不必有序,但是块与块之间必须是有序的

适合动态的 因为往里插入 不用再排序

Pasted image 20250107100720.png|400

二叉排序树 ---- 中序遍历

查找代码:

bool find(TreeNode root,int value){
	while(root!=nullptr){
		if(root->data==value)
			return true;
		if(root->data<value)
			root=root->right;
		if(root->data>value)
			root=root->left;
	}
	return false;
}

构建

TreeNode* insert(TreeNode* root,int value){
	while (temp != NULL) {
			if (val < temp->data) {  //如果要放入的值小于根节点
				if (temp->left == NULL) {  //根节点左孩为空,就直接放入
					temp->left = node;
					return;
				}
				else {
					temp = temp->left;  //根节点左孩不为空,就指向下一个左孩节点
				}
			}
			else {
				if (temp->right == NULL) { //右孩为空,直接放入
					temp->right = node;
					return;
				}
				else {
					temp = temp->right;  //右孩不为空,指向下一个右孩节点
				}
			}
		}
}

平衡二叉树生成过程 左子树和右子树深度不超过1

构造4 5 7 2 1 3 6

Pasted image 20250107102851.png

哈希函数

一般哈希函数是取余

处理冲突的方法一般考的话就两种

链地址法:

Pasted image 20250107105802.png|500